from django.db.models import Q
from django.shortcuts import redirect
from rest_framework.generics import ListAPIView

from search.models import Record
from search.serializers import RecordSerializer


def show_index(request):
    return redirect('/static/html/index.html')


class RecordView(ListAPIView):
    serializer_class = RecordSerializer
    # 如果不希望使用默认的分页，可以将pagination_class属性修改为None即可
    # pagination_class = None

    def get_queryset(self):
        queryset = Record.objects.filter(is_deleted=False) \
            .select_related('car').order_by('-makedate') \
            .defer('is_deleted', 'deleted_time', 'updated_time')
        keyword = self.request.GET.get('kw', '').upper().strip()
        if keyword:
            queryset = queryset.filter(
                Q(car__carno__startswith=keyword) | Q(car__owner__contains=keyword)
            )
        return queryset
